package com.ctvit.cch.ai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ctvit.cch.ai.pojo.dto.AutoCategoryDTO;
import com.ctvit.cch.ai.pojo.dto.CreativeEvaluationDTO;
import com.ctvit.cch.ai.pojo.dto.GenerateCreationDTO;
import com.ctvit.cch.ai.pojo.dto.GenerateScriptDTO;
import com.ctvit.cch.ai.pojo.dto.GenerateShotDTO;
import com.ctvit.cch.ai.pojo.vo.AutoCategoryVO;
import com.ctvit.cch.ai.pojo.vo.CreativeEvaluationVO;
import com.ctvit.cch.ai.pojo.vo.GenerateCreationVO;
import com.ctvit.cch.ai.pojo.vo.GenerateScriptVO;
import com.ctvit.cch.ai.pojo.vo.GenerateShotVO;
import com.ctvit.cch.ai.service.ILlmService;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.openai.OpenAiChatModel;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 大模型处理服务实现类
 * <p>
 * 该类实现了大模型处理相关的业务逻辑
 *
 * @author heyingcheng
 * @date 2025/07/30
 */
@Slf4j
@Service
public class ILlmServiceImpl implements ILlmService {

    private static final Pattern CONTROL_CHARS = Pattern.compile("[\\x00-\\x1F\\x7F&&[^\\n\\r\\t]]");

    private final OpenAiChatModel siliconChatModel;

    public ILlmServiceImpl(OpenAiChatModel siliconChatModel) {
        this.siliconChatModel = siliconChatModel;
    }

    /**
     * 处理AI返回的文本，确保它能被fastjson正确解析
     * 
     * @param chatResponse AI聊天响应对象
     * @return 处理后的纯JSON字符串，可被fastjson直接解析
     */
    private String processJsonResponse(ChatResponse chatResponse) {
        String rawText = StringUtils.defaultString(chatResponse.aiMessage().text()).trim();
        log.info("rawText:[{}]", rawText);

        // 1. 安全移除外层代码块（仅开头和结尾）
        if (rawText.startsWith("```json")) {
            rawText = rawText.substring(7);
        } else if (rawText.startsWith("```")) {
            rawText = rawText.substring(3);
        }
        if (rawText.endsWith("```")) {
            rawText = rawText.substring(0, rawText.length() - 3);
        }
        rawText = rawText.trim();

        // 2. 清理空白字符
        String processedJsonText = rawText
                // 移除空行
                .replaceAll("(?m)^\\s+$", "")
                // 多个换行保留最多两个
                .replaceAll("\n{3,}", "\n\n")
                // 移除行首空白
                .replaceAll("^\\s+", "")
                // 移除行尾空白
                .replaceAll("\\s+$", "");

        // 3. 移除控制字符
        processedJsonText = CONTROL_CHARS.matcher(processedJsonText).replaceAll("");

        log.info("processedJsonText:[{}]", processedJsonText);
        return processedJsonText;
    }

    /**
     * 自动分类方法
     * <p>
     * 根据输入的文本内容，使用自然语言处理技术自动对其进行分类
     *
     * @param dto 包含待分类文本信息的数据传输对象
     * @return AutoCategoryVO 分类结果的视图对象，包含分类标签和置信度等信息
     */
    @Override
    public AutoCategoryVO categorize(AutoCategoryDTO dto) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(AutoCategoryDTO.SYSTEM_MESSAGE_TEXT));
        messages.add(UserMessage.from(AutoCategoryDTO.USER_MESSAGE_TEMPLATE
                .formatted(StringUtils.defaultString(dto.getTitle()), StringUtils.defaultString(dto.getSummary()),
                        StringUtils.defaultString(dto.getCategoryNames()))));

        ChatResponse chatResponse = siliconChatModel.chat(messages);
        String categoryJsonText = processJsonResponse(chatResponse);
        return JSON.parseObject(categoryJsonText, AutoCategoryVO.class);
    }

    /**
     * 该方法用于调用AI模型对创意内容进行评估。首先构建系统提示和用户消息，然后通过siliconChatModel发送请求并获取AI回复的JSON文本，最后将该JSON解析为CreativeEvaluationVO对象返回。
     *
     * @param dto 创意评估数据传输对象
     * @return {@link CreativeEvaluationVO } 创意评估结果对象
     */
    @Override
    public CreativeEvaluationVO evaluate(CreativeEvaluationDTO dto) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(CreativeEvaluationDTO.SYSTEM_MESSAGE_TEXT));
        messages.add(UserMessage.from(CreativeEvaluationDTO.USER_MESSAGE_TEMPLATE
                .formatted(StringUtils.defaultString(dto.getTitle()), StringUtils.defaultString(dto.getSummary()))));

        ChatResponse chatResponse = siliconChatModel.chat(messages);
        String evaluationJsonText = processJsonResponse(chatResponse);
        return JSON.parseObject(evaluationJsonText, CreativeEvaluationVO.class);
    }

    @Override
    public List<GenerateCreationVO> generateCreation(GenerateCreationDTO dto) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(GenerateCreationDTO.SYSTEM_MESSAGE_TEXT));
        messages.add(UserMessage.from(GenerateCreationDTO.USER_MESSAGE_TEMPLATE.formatted(
                StringUtils.defaultString(dto.getTitle()),
                StringUtils.defaultString(dto.getDescription()),
                StringUtils.defaultString(dto.getRemark()))));

        ChatResponse chatResponse = siliconChatModel.chat(messages);
        String creationJsonText = processJsonResponse(chatResponse);
        return JSON.parseArray(creationJsonText, GenerateCreationVO.class);
    }

    @Override
    public List<GenerateScriptVO> generateScript(GenerateScriptDTO dto) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(GenerateScriptDTO.SYSTEM_MESSAGE_TEXT));
        messages.add(UserMessage.from(GenerateScriptDTO.USER_MESSAGE_TEMPLATE.formatted(
                StringUtils.defaultString(dto.getScriptTitle()),
                StringUtils.defaultString(dto.getScriptTheme()),
                StringUtils.defaultString(dto.getScriptDescription()),
                StringUtils.defaultString(dto.getScriptContent()),
                StringUtils.defaultString(dto.getDurationRange()),
                StringUtils.defaultString(dto.getToneStyle()),
                StringUtils.defaultString(dto.getAspectRatio()),
                StringUtils.defaultString(dto.getCopyStructure()),
                StringUtils.defaultString(dto.getAdditionalContent()))));

        ChatResponse chatResponse = siliconChatModel.chat(messages);
        String scriptJsonText = processJsonResponse(chatResponse);
        return JSON.parseArray(scriptJsonText, GenerateScriptVO.class);
    }

    @Override
    public List<GenerateShotVO> generateShot(GenerateShotDTO dto) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(SystemMessage.from(GenerateShotDTO.SYSTEM_MESSAGE_TEXT));
        messages.add(UserMessage.from(GenerateShotDTO.USER_MESSAGE_TEMPLATE.formatted(
                StringUtils.defaultString(ObjectUtils.defaultIfNull(dto.getSceneIndex(), 0).toString()),
                StringUtils.defaultString(dto.getSceneName()),
                StringUtils.defaultString(ObjectUtils.defaultIfNull(dto.getSceneDuration(), 5).toString()),
                StringUtils.defaultString(dto.getSceneDescription()),
                StringUtils.defaultString(dto.getEventDescription()),
                StringUtils.defaultString(dto.getCharacters()),
                StringUtils.defaultString(dto.getCharacterDialogue()),
                StringUtils.defaultString(dto.getSidebarContent()))));

        ChatResponse chatResponse = siliconChatModel.chat(messages);
        String shotJsonText = processJsonResponse(chatResponse);
        return JSON.parseArray(shotJsonText, GenerateShotVO.class);
    }

}
